package com.example.onlinefood.controller;

import com.example.onlinefood.domain.Order;
import com.example.onlinefood.domain.OrderEvaluation;
import com.example.onlinefood.domain.OrderItem;
import com.example.onlinefood.service.OrderService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/v1")
@Validated
public class OrderController {
    @Resource
    private OrderService orderService;

    public static class CreateOrderRequest {
        public Integer userId;
        public Integer restaurantId;
        public @NotBlank(message = "deliveryAddress不能为空") String deliveryAddress;
        public String contactPhone;
        public List<Item> items;
    }
    public static class Item {
        public Integer menuItemId;
        public Integer quantity;
        public BigDecimal price;
    }

    @PostMapping("/orders")
    public ResponseEntity<?> create(@Valid @RequestBody CreateOrderRequest req) {
        Order order = new Order();
        order.setUserId(req.userId);
        order.setRestaurantId(req.restaurantId);
        BigDecimal total = BigDecimal.ZERO;
        new java.util.ArrayList<>(req.items).forEach(i -> {
        });
        for (Item i : req.items) {
            total = total.add(i.price.multiply(new BigDecimal(i.quantity)));
        }
        order.setTotalAmount(total);
        order.setStatus("pending");
        order.setDeliveryAddress(req.deliveryAddress);
        order.setContactPhone(req.contactPhone);

        java.util.ArrayList<OrderItem> items = new java.util.ArrayList<>();
        for (Item i : req.items) {
            OrderItem oi = new OrderItem();
            oi.setMenuItemId(i.menuItemId);
            oi.setQuantity(i.quantity);
            oi.setPrice(i.price);
            items.add(oi);
        }

        Integer id = orderService.createOrder(order, items);
        return ResponseEntity.ok(id);
    }

    @GetMapping("/orders")
    public ResponseEntity<List<Order>> list(@RequestParam Integer userId) {
        return ResponseEntity.ok(orderService.listByUser(userId));
    }

    @GetMapping("/orders/{id}")
    public ResponseEntity<?> detail(@PathVariable Integer id) {
        Order order = orderService.getById(id);
        if (order == null) {
            return ResponseEntity.notFound().build();
        }
        List<OrderItem> items = orderService.listItems(id);
        
        // 创建一个包含订单和订单项的响应对象
        java.util.Map<String, Object> response = new java.util.HashMap<>();
        response.put("order", order);
        response.put("items", items);
        
        return ResponseEntity.ok(response);
    }
    
    @PutMapping("/orders/{id}/cancel")
    public ResponseEntity<?> cancel(@PathVariable Integer id, @RequestParam Integer userId) {
        boolean success = orderService.cancelOrder(id, userId);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body("无法取消订单，可能已超过取消时间或状态不允许");
        }
    }
    
    @DeleteMapping("/orders/{id}")
    public ResponseEntity<?> delete(@PathVariable Integer id, @RequestParam Integer userId) {
        boolean success = orderService.deleteOrder(id, userId);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body("无法删除订单，可能订单不存在、不属于您或状态不允许删除");
        }
    }
    
    @PutMapping("/orders/{id}/status")
    public ResponseEntity<?> updateStatus(@PathVariable Integer id, @RequestParam Integer userId, @RequestBody StatusUpdateRequest req) {
        boolean success = orderService.updateOrderStatus(id, userId, req.newStatus);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body("无法更新订单状态，可能订单不存在、不属于您或状态不允许更新");
        }
    }
    
    public static class StatusUpdateRequest {
        public String newStatus;
    }
    
    public static class OrderEvaluationRequest {
        public Integer userId;
        public Integer score;
        public String content;
    }
    
    // 添加订单评价
    @PutMapping("/orders/{id}/evaluate")
    public ResponseEntity<?> evaluateOrder(@PathVariable Integer id, @Valid @RequestBody OrderEvaluationRequest req) {
        try {
            orderService.addOrderEvaluation(id, req.userId, req.score, req.content);
            return ResponseEntity.ok().build();
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    // 获取订单评价
    @GetMapping("/orders/{id}/evaluate")
    public ResponseEntity<?> getOrderEvaluation(@PathVariable Integer id) {
        OrderEvaluation evaluation = orderService.getOrderEvaluation(id);
        if (evaluation == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(evaluation);
    }
}


